/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.merak.core.text.json.jsonfiers;

import java.util.Iterator;
import java.util.Map;

import org.merak.core.text.json.JsonContext;

public class MapJsonfier extends Jsonfier {

	//~ Methods //////////////////////////////////////////////////////////////////
	//****************************************************************************
	@Override
	public void render(Object object,JsonContext context) throws Exception {

		Map<?,?>     map  = (Map<?,?>) object;
		StringBuffer json = context.getBuffer();

		// Base case
		if (map.isEmpty()){
			json.append("{}");
			return;
		}

		// Choose the correct jsonfier for values in the map
		Iterator<?> iter     = map.values().iterator();
		Jsonfier    jsonfier = context.getJsonfier(iter.next());

		// For non empty maps, Choose the right jsonfier for map's values
		json.append('{');
		for (Map.Entry<?,?> entry : map.entrySet()) {
			json.append('"').append(entry.getKey()).append("\":");
			jsonfier.render(entry.getValue(), context);
			json.append(',');
		}
		json.setCharAt(json.length()-1,'}');

	}
	//****************************************************************************

}
